package com.fccommunity.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fccommunity.R;

import java.lang.ref.WeakReference;

/**
 * Created by Administrator on 2016/4/24 0024.
 *
 * 用法：
 * 1.xml布局中使用该类
 * 2.drawable/下添加dot_white.xml和dot_red.xml
 * 3.layout/下添加view_auto_scroll_viewpager.xml
 * 4.获取AutoScrollViewPager对象
 * 5.给AutoScrollViewPager添加PagerAdapter
 * 6.PagerAdapter实现getPageTitle方法
 * 7.调用AutoScrollViewPager的startAutoScroll方法
 * 8.父类主动调用AutoScrollViewPager的stopAutoScroll方法
 */
public class AutoScrollViewPager extends RelativeLayout {

    private static final String TAG = AutoScrollViewPager.class.getSimpleName();

    private Context      mContext;
    private ViewPager mViewPager;
    private TextView     mTitle;
    private LinearLayout mIndicatorContainer;

    private ViewPager.OnPageChangeListener mPagerChangeListener;

    private PagerAdapter mPagerAdapter;

    private int mCurrentPosition;   //ViewPager当前的位置
    private int count;  // ViewPager中Page的个数

    private int mDotMargin;
    private int mDotWidth;

    private LoopHandler mHandler;

    public static final int DURATION    = 3000; // ViewPager每3秒跳到下一个Page
    public static final int SCROLL_WHAT = 200;
    public boolean isAutoScroll;

    public AutoScrollViewPager(Context context) {
        this(context, null);
    }

    public AutoScrollViewPager(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AutoScrollViewPager(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mContext = context;
        View.inflate(context, R.layout.view_auto_scroll_viewpager, this);

        initView();
        initListener();
        initData();
    }

    private void initView() {
        mViewPager = (ViewPager) findViewById(R.id.auto_scroll_viewpager);
        mTitle = (TextView) findViewById(R.id.auto_scroll_title);
        mIndicatorContainer = (LinearLayout) findViewById(R.id.auto_scroll_indicator_container);
    }

    private void initListener() {
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                /** 调用用户指定的监听器 */
                if (mPagerChangeListener != null) {
                    mPagerChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
                }
            }

            @Override
            public void onPageSelected(int position) {
                mCurrentPosition = position;

                mTitle.setText(mPagerAdapter.getPageTitle(mCurrentPosition));

                refreshIndicator();

                /** 调用用户指定的监听器 */
                if (mPagerChangeListener != null) {
                    mPagerChangeListener.onPageSelected(position);
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                /** 调用用户指定的监听器 */
                if (mPagerChangeListener != null) {
                    mPagerChangeListener.onPageScrollStateChanged(state);
                }
            }
        });
    }

    private void initData() {
        WindowManager  manager    = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        float scalingFactor = outMetrics.density;

        mDotMargin = (int) (0.5f + scalingFactor * 4);
        mDotWidth = (int) (0.5f + scalingFactor * 8);

        mHandler = new LoopHandler(this);

        mCurrentPosition = 0;
    }

    public void setIndicatorVisable(boolean indicatorVisable){
        if(indicatorVisable){
            mIndicatorContainer.setVisibility(View.VISIBLE);
        }else{
            mIndicatorContainer.setVisibility(View.GONE);
        }
    }

    private void createIndicator() {
        mIndicatorContainer.removeAllViews();

        View dot;

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mDotWidth, mDotWidth);
        params.leftMargin = mDotMargin;
        params.rightMargin = mDotMargin;
        for (int i = 0; i < count; ++i) {
            dot = new View(mContext);
            dot.setLayoutParams(params);
            if (i == mCurrentPosition) {
                dot.setBackgroundResource(R.drawable.dot_red);
            } else {
                dot.setBackgroundResource(R.drawable.dot_white);
            }
            mIndicatorContainer.addView(dot);
        }
    }

    private void refreshIndicator() {
        View view;
        for (int i = 0; i < count; ++i) {
            view = mIndicatorContainer.getChildAt(i);
            if (i == mCurrentPosition) {
                view.setBackgroundResource(R.drawable.dot_red);
            } else {
                view.setBackgroundResource(R.drawable.dot_white);
            }
        }
    }


    public void setCurrentItem(int item) {
        mCurrentPosition = item;
        mViewPager.setCurrentItem(mCurrentPosition);
    }

    public void setAdapter(PagerAdapter adapter) {
        mPagerAdapter = adapter;
        count = mPagerAdapter.getCount();
        if (count < 0) {
            Log.e(TAG, "AutoScrollViewPager的PagerAdapter数据不能小于0");
            return;
        }
        createIndicator();
        mTitle.setText(mPagerAdapter.getPageTitle(mCurrentPosition));
        mViewPager.setAdapter(mPagerAdapter);
    }

    public void addOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
        mPagerChangeListener = listener;
    }

    public void startAutoScroll() {
        isAutoScroll = true;
        mHandler.removeMessages(SCROLL_WHAT);
        mHandler.sendEmptyMessageDelayed(SCROLL_WHAT, DURATION);
    }

    public void stopAutoScroll() {
        isAutoScroll = false;
        mHandler.removeMessages(SCROLL_WHAT);
    }

    public void scrollOnce() {
        int nextPosition = (mCurrentPosition + 1) % count;
        if (nextPosition == 0) {
            mViewPager.setCurrentItem(nextPosition, false);
        } else {
            mViewPager.setCurrentItem(nextPosition);
        }
    }

    static class LoopHandler extends Handler {
        private WeakReference<AutoScrollViewPager> ref;

        public LoopHandler(AutoScrollViewPager autoScrollViewPager) {
            super();
            ref = new WeakReference<AutoScrollViewPager>(autoScrollViewPager);
        }

        @Override
        public void handleMessage(Message msg) {
            AutoScrollViewPager autoScrollViewPager = ref.get();
            if (null == autoScrollViewPager) {
                return;
            }

            if (msg.what == SCROLL_WHAT) {
                autoScrollViewPager.scrollOnce();
                autoScrollViewPager.startAutoScroll();
            }
        }
    }
}
